import time
from datetime import datetime, timedelta

from flask import render_template, request, jsonify, current_app, session, redirect, url_for, g

from info import constants, db
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import admin_blue


# 登录界面
@admin_blue.route("/login", methods=["GET", "POST"])
def admin_login():
    if request.method == "GET":
        # 已登录管理员直接跳转主页
        # 从session中获取user_id和is_admin
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", False)

        if user_id and is_admin:
            return redirect("/admin/index")
        return render_template("admin/login.html")
    """
    1、获取用户名、密码
    2、验证
    3、跳转至主页
    """
    user_name = request.form.get("username")
    password = request.form.get("password")

    if not all([user_name, password]):
        return render_template("admin/login.html", errmsg="参数不足")

    try:
        user = User.query.filter(User.mobile == user_name).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="数据查询失败")

    if not user:
        return render_template("admin/login.html", errmsg="用户不存在")

    if not user.check_passowrd(password):
        return render_template("admin/login.html", errmsg="用户名或密码不正确")

    if not user.is_admin:
        return render_template("admin/login.html", errmsg="用户权限不足")

    # 保持用户登录状态
    session["user_id"] = user.id
    session["mobile"] = user.nick_name
    session["nick_name"] = user.mobile
    session["is_admin"] = user.is_admin

    return redirect(url_for("admin.admin_index"))


# 后端主页展示
@admin_blue.route("/index")
@user_login_data
def admin_index():
    user = g.user
    data = {
        "user": user.to_admin_dict()
    }
    return render_template("admin/index.html", data=data)


# 已注册用户统计及活跃用户曲线
@admin_blue.route("/user_count")
@user_login_data
def user_count():
    """
    1、从数据库查询总注册人数
    2、从数据库查询用户月增人数,根据用户创建时间，datetime.now()，是datetime.datetime类型对象大于每月1日
    3、从数据库查询用户日增人数
    4、返回数据
    :return:
    """
    # 查询总人数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 月增人数
    mon_count = 0
    # 获取每月1日的time.struct_time对象，(tm_year=2019, tm_mon=6, tm_mday=5, tm_hour=19, tm_min=19, tm_sec=23, tm_wday=2, tm_yday=156, tm_isdst=0)
    now = time.localtime()
    try:
        # 获得每月1日的时间字符串
        mon_begin_str = "%d-%02d-01" % (now.tm_year, now.tm_mon)
        # 解析成datetime对象
        mon_begin_datetime = datetime.strptime(mon_begin_str, "%Y-%m-%d")
        # 跟用户创建对象一致，可以进行比较大小
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_datetime).count()
    except Exception as e:
        current_app.logger.error(e)

    # 日增人数
    day_count = 0
    try:
        day_time_str = "%d-%02d-%02d" % (now.tm_year, now.tm_mon, now.tm_mday)
        day_begin_datetime = datetime.strptime(day_time_str, "%Y-%m-%d")
        day_count = User.query.filter(User.is_admin == False, User.create_time >= day_begin_datetime).count()
    except Exception as e:
        current_app.logger.error(e)

    # 用户图表信息，活跃日期及活跃数量
    # 活跃日期需获取当天0点时间
    now_date_str = datetime.now().strftime("%Y-%m-%d")
    now_datetime = datetime.strptime(now_date_str, "%Y-%m-%d")

    active_date = []
    active_count = []
    # for 循环获取当天的0点跟下一天的0点，用户登录时间在两者之间即为当天活跃人数
    for i in range(0, 31):
        begin_time = now_datetime - timedelta(days=i)
        end_time = now_datetime - timedelta(days=i - 1)
        active_date.append(begin_time.strftime("%Y-%m-%d"))

        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_time,
                                      User.last_login < end_time).count()
        except Exception as e:
            current_app.logger.error(e)
        active_count.append(count)

    active_date.reverse()
    active_count.reverse()

    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_date": active_date,
        "active_count": active_count
    }

    return render_template("admin/user_count.html", data=data)


# 已注册用户列表
@admin_blue.route("/user_list")
@user_login_data
def user_list():
    # 获取当前页码
    p = request.args.get("p", 1)

    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 根据页码分页对象
    users = []
    page = 1
    pages = 1
    try:
        paginate = User.query.order_by(User.last_login.desc()).paginate(p, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        page = paginate.page
        pages = paginate.pages
        users = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    # 数据转化
    user_dict_list = [user.to_admin_dict() for user in users]
    data = {
        "users": user_dict_list,
        "page": page,
        "pages": pages
    }

    return render_template("admin/user_list.html", data=data)


# 用户发布新闻审核列表
@admin_blue.route("/news_review")
@user_login_data
def news_review():
    # 点击搜索按钮，发起form表单提交，get请求方式
    keywords = request.args.get("keywords", "")
    # 获取当前页码
    p = request.args.get("p", 1)

    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 根据页码分页对象
    news_list = []
    page = 1
    pages = 1
    filters = [News.status != 0]
    try:
        if keywords:
            filters.append(News.title.contains(keywords))
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(p,
                                                                                          constants.ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                          False)
        page = paginate.page
        pages = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    # 数据转化
    news_dict_list = [news.to_review_dict() for news in news_list]
    data = {
        "news_list": news_dict_list,
        "page": page,
        "pages": pages
    }

    return render_template("admin/news_review.html", data=data)


# 审核界面
@admin_blue.route("/news_review_detail", methods=["get", "post"])
@user_login_data
def news_review_detail():
    # 如是get请求，将新闻数据返回
    if request.method == "GET":
        # 获取新闻id
        news_id = request.args.get("news_id")
        # 校验参数
        if not news_id:
            return render_template("admin/news_review_detail.html", data={"errmsg": "参数错误"})
        try:
            news_id = int(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template("admin/news_review_detail.html", data={"errmsg": "参数错误"})
        #  查询新闻
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template("admin/news_review_detail.html", data={"errmsg": "数据查询错误"})
        if not news:
            return render_template("admin/news_review_detail.html", data={"errmsg": "未查询到此新闻"})

        data = {"news": news.to_dict()}
        return render_template("admin/news_review_detail.html", data=data)

    else:
        """
        1、获取参数news_id,action
        2、验证参数
        3、修改新闻状态数据
        4、提交数据库
        5、返回结果
        """
        news_id = request.json.get("news_id")
        action = request.json.get("action")

        if not all([news_id, action]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        if action not in ("accept", "reject"):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

        if not news:
            return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

        if action == "accept":
            news.status = 0
        else:
            # 拒绝需要原因
            reason = request.json.get("reason")
            if not reason:
                return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
            news.reason = reason
            news.status = -1
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
        return jsonify(errno=RET.OK, errmsg="操作成功")


# 新闻板式编辑，新闻列表展示
@admin_blue.route("/news_edit", methods=["get", "post"])
@user_login_data
def news_edit():
    """
    分页展示，转换数据，返回模板html和数据列表，再添加搜索功能
    :return: 
    """
    # 点击搜索按钮，发起form表单提交，get请求方式
    keywords = request.args.get("keywords", "")
    # 获取当前页码
    p = request.args.get("p", 1)

    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 根据页码分页对象
    news_list = []
    page = 1
    pages = 1
    filters = [News.status == 0]
    try:
        if keywords:
            filters.append(News.title.contains(keywords))
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(p,
                                                                                          constants.ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                          False)
        page = paginate.page
        pages = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    # 数据转化
    news_dict_list = [news.to_basic_dict() for news in news_list]
    data = {
        "news_list": news_dict_list,
        "page": page,
        "pages": pages
    }

    return render_template("admin/news_edit.html", data=data)


# 新闻编辑界面跳转详细接麦你
@admin_blue.route("/news_edit_detail", methods=["get", "post"])
@user_login_data
def news_edit_detail():
    # 如是get请求，将新闻数据返回
    if request.method == "GET":
        # 获取新闻id
        news_id = request.args.get("news_id")
        # 校验参数
        if not news_id:
            return render_template("admin/news_edit_detail.html", data={"errmsg": "参数错误"})
        try:
            news_id = int(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template("admin/news_edit_detail.html", data={"errmsg": "参数错误"})
        #  查询新闻
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        if not news:
            return render_template("admin/news_edit_detail.html", data={"errmsg": "未查询到此新闻"})

        # 查询新闻分类
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        # 解析分类数据
        category_list = []
        for category in categories:
            category_dict = category.to_dict()
            category_dict["is_selected"] = False
            if category.id == news.category_id:
                category_dict["is_selected"] = True
            category_list.append(category_dict)

        category_list.pop(0)

        data = {"news": news.to_dict(),
                "categories": category_list
                }
        return render_template("admin/news_edit_detail.html", data=data)

    # 新闻修改后数据重新提交
    else:
        """
        1、获取参数news_id,action
        2、验证参数
        3、修改新闻状态数据
        4、提交数据库
        5、返回结果
        """
        # 获取参数
        news_id = request.form.get("news_id")
        title = request.form.get("title")
        category_id = request.form.get("category_id")
        digest = request.form.get("digest")
        index_image = request.files.get("index_image")
        content = request.form.get("content")

        # 校验参数
        if not all([news_id, title, category_id, digest, content]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误1")
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

        if not news:
            return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

        # 读取图片信息
        if index_image:
            try:
                index_image = index_image.read()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.PARAMERR, errmsg="图片读取错误")

            # 上传至七牛云
            try:
                key = storage(index_image)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.THIRDERR, errmsg="图片上传失败")
            # 如果修改图片，修改新闻数据
            news.index_image_url = constants.QINIU_DOMIN_PREFIX + key

        # 将数据添加至数据库
        news.title = title
        news.category_id = category_id
        news.digest = digest
        news.content = content

        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
        return jsonify(errno=RET.OK, errmsg="操作成功")


# 新闻分类展示
@admin_blue.route("/news_type", methods=["get", "post"])
@user_login_data
def news_type():
    if request.method == "GET":
        # 查询新闻分类
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        # 解析分类数据
        category_list = []
        for category in categories:
            category_dict = category.to_dict()
            category_list.append(category_dict)

        category_list.pop(0)
        data = {
            "categories": category_list
        }
        return render_template("admin/news_type.html", data=data)

    # 编辑及添加功能
    else:
        category_id = request.json.get("id")
        category_name = request.json.get("name")
        # 校验参数
        if not category_name:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        # 如果有分类id,则为修改分类，否则为新增分类
        if category_id:
            # 根据id查询分类
            try:
                category = Category.query.get(category_id)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

            if not category:
                return jsonify(errno=RET.DATAERR, errmsg="未查询到分类信息")

            category.name = category_name

        # 新增分类
        else:
            category = Category()
            category.name = category_name
            db.session.add(category)

        # 提交数据库
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库提交错误")
        return jsonify(errno=RET.OK, errmsg="ok")

# 退出登录
@admin_blue.route("/logout")
def logout():
    """
    1、后端删除session中的值
    2、返回结果
    :return:
    """
    session.pop("user_id", None)
    session.pop("nick_name", None)
    session.pop("mobile", None)
    session.pop("is_admin", None)

    return redirect("/")